<template>
  <CallBack />
  <div class="health-view">
    <!-- 全局加载组件 -->
    <LoadingOverlay />
    <div class="health-container">
      <!-- 状态显示区域 -->
      <div class="health-status-area">
        <!-- 1. 显示到期时间 (优先级最高) -->
        <div v-if="priceSetting.month_time" class="status-block expiry-time">
          <span class="status-icon">⏱️</span>
          <span class="status-text">{{ t('your_month_card_will_expire_in') }} {{ priceSetting.month_time }} {{ t('days')
            }}</span>
        </div>

        <!-- 2. 显示免费次数 -->
        <div v-else-if="priceSetting.free_nums > 0" class="status-block free-count">
          <span class="status-icon">🎁</span>
          <span class="status-text">{{ t('you_have') }} {{ priceSetting.free_nums }} {{
            t('free_consultation_opportunities') }}</span>
        </div>

        <!-- 3. 显示次卡剩余次数 -->
        <div v-else-if="priceSetting.once_nums > 0" class="status-block usage-count">
          <span class="status-icon">🎫</span>
          <span class="status-text">{{ t('your_once_card_still_has') }} {{ priceSetting.once_nums }} {{
            t('usage_opportunities') }}</span>
        </div>

        <!-- 4. 显示充值按钮 -->
        <div v-else class="status-block payment-options">
          <div class="payment-title">{{ t('please_select_payment_method') }}</div>
          <div class="payment-buttons">
            <el-space wrap>
              <button class="payment-button once-card" @click="handleRechargeClick('once')">{{ t('recharge_once_card')
                }}</button>
              <button class="payment-button month-card" @click="handleRechargeClick('month')" v-if="map.month_key">{{
                t('recharge_month_card') }}</button>
            </el-space>
          </div>
        </div>
      </div>
      <!-- 健康咨询类别选择 -->
      <div class="health-category">
        <h3 class="health-section-title">— {{ t('select_consultation_item') }} —</h3>
        <div class="health-dropdown">
          <div class="health-category-selector" @click="toggleDropdown">
            <span v-if="!selectedHealthQuestion" class="placeholder">{{ t('please_select_consultation_item') }}</span>
            <span v-else>{{ t(selectedHealthQuestion.title) }}</span>
            <span class="selector-icon" :class="{ 'rotated': showDropdown }">▼</span>
          </div>
          <div class="health-dropdown-menu" v-show="showDropdown">
            <div v-for="question in healthQuestions" :key="question.id" class="health-dropdown-item"
              @click="selectHealthQuestion(question)">
              {{ t(question.title) }}
            </div>
          </div>
        </div>
      </div>

      <!-- 健康咨询问题表单 -->
      <div v-if="selectedHealthQuestion" class="health-form">
        <div v-for="(prompt, index) in selectedHealthQuestion.prompts" :key="index" class="health-form-item">
          <label>{{ t(prompt) }}:</label>
          <!-- 如果字段包含date，则显示日期选择器 -->
          <template v-if="selectedHealthQuestion.questions[index].toLowerCase().includes('date')">
            <el-date-picker v-model="healthInputs[selectedHealthQuestion.questions[index]]" type="date"
              :placeholder="t('please_select') + t(prompt)" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
              class="health-date-input" />
          </template>
          <!-- 其他字段显示普通输入框 -->
          <template v-else>
            <input type="text" v-model="healthInputs[selectedHealthQuestion.questions[index]]"
              :placeholder="t('please_input') + t(prompt)" class="health-input" />
          </template>
        </div>
      </div>

      <!-- 图片上传区域根据某些分类才显示 -->
      <div class="health-upload" v-if="[19].includes(healthCategoryId)">
        <h3 class="health-section-title">{{ t('support_only_face_and_tongue_images') }}</h3>
        <div class="upload-area">
          <div v-for="(image, index) in healthImages" :key="index" class="uploaded-image">
            <img :src="image.url" alt="上传图片" />
            <div class="image-delete" @click="removeHealthImage(index)">×</div>
          </div>
          <div class="upload-button" @click="triggerUpload" v-if="healthImages.length < 4">
            <span class="upload-icon">+</span>
            <span class="upload-text">{{ t('upload_images') }}</span>
            <input type="file" ref="fileInput" accept="image/*" multiple @change="handleFileUpload"
              style="display: none" />
          </div>
        </div>
      </div>

      <!-- 查询结果区域 -->
      <div v-if="showResult" class="health-result-section">
        <h3 class="health-section-title">{{ t('consultation_result') }}</h3>
        <div class="result-content">
          <!-- 使用共通化的打字机效果组件 -->
          <TypewriterText :parsedResult="parsedResult" :displayedText="displayedText" :currentSection="currentSection"
            :currentElement="currentElement" :isTyping="isTyping" :showResult="showResult" />
        </div>
      </div>



      <!-- 提交按钮 -->
      <div class="health-submit"
        v-if="priceSetting.free_nums > 0 || priceSetting.once_nums > 0 || priceSetting.month_time">
        <button class="submit-button" @click="submitHealthConsultation"
          :disabled="!selectedHealthQuestion || isAllFieldsEmpty()">
          {{ t('submit_consultation') }}
        </button>
      </div>
    </div>
    <!-- 支付对话框组件 -->
    <PaymentDialog ref="paymentDialog" :packageInfo="currentPackage" @success="handlePaymentSuccess"
      @close="handlePaymentClose" @cancel="handlePaymentCancel" @error="handlePaymentError" />
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, reactive, watch } from 'vue';
import LoadingOverlay from '@/components/common/LoadingOverlay.vue';
import { ElMessage } from 'element-plus';
import { getQuestionList, submitHealthQuery, getPredict, getUserCombo } from '@/api/chat';
import TypewriterText from '@/components/common/TypewriterText.vue';
import { useTypewriter } from '@/hooks/useTypewriter';
import { useLoadingStore } from '@/store/loadingStore';
import { useRoute } from 'vue-router';
import { useUserStore } from '@/store/userStore';
import { useTeamType } from '@/hooks/useTeamType';
import PaymentDialog from '@/components/common/PaymentDialog.vue';
import { useLanguageStore } from '@/store/languageStore'
import { useTranslateData } from '@/hooks/useTranslateData';
import CallBack from '@/components/common/CallBack.vue';
import useLogin from '@/hooks/useLogin';
const { t } = useLanguageStore();
const { translateObjectProperties } = useTranslateData();
const teamType = useTeamType()
const { toogleLoginModal } = useLogin()
// 健康咨询相关
const healthQuestions = ref([]);
const showDropdown = ref(false);
const selectedHealthQuestion = ref(null);
const healthInputs = ref({});
const healthImages = ref([]);
const route = useRoute();
const healthCategoryId = ref(route.query.categoryId || 19); // 默认健康咨询分类ID

const map = teamType.getMapStr(healthCategoryId.value)

const priceSetting = reactive({
  free_nums: 0,   //免费次数
  oncepay: 0,     //次卡费用
  monpay: 0,      //月卡费用
  once_nums: 0,   //次卡次数
  month_time: 0,  //月卡到期日期
})

// 根据分类ID获取类型
const userStore = useUserStore();
// 使用加载状态store
const loadingStore = useLoadingStore();

watch(() => userStore.isLoggedIn, () => {
  if (userStore.isLoggedIn) {
    getUserCard();
  }
})

// 判断所有字段是否为空
const isAllFieldsEmpty = () => {
  return Object.values(healthInputs.value).every(value => !value);
};

// 使用打字机效果hook
const {
  parsedResult,
  displayedText,
  currentSection,
  currentElement,
  isTyping,
  showResult,
  setResultData,
  startTypingEffect,
  resetTypewriter,
  applyHighlight
} = useTypewriter();

// 切换下拉菜单显示状态
const toggleDropdown = () => {
  showDropdown.value = !showDropdown.value;
};

// 点击外部关闭下拉菜单
const closeDropdownOnClickOutside = (event) => {
  const dropdown = document.querySelector('.health-dropdown');
  if (dropdown && !dropdown.contains(event.target)) {
    showDropdown.value = false;
  }
};


// 监听点击事件
onMounted(async () => {
  document.addEventListener('click', closeDropdownOnClickOutside);
  // 获取问题列表
  await fetchHealthQuestions();
  await getUserCard();
});

const handlePaymentClose = async () => {
  await getUserCard();
}

// 获取当前用户资费卡
const getUserCard = async () => {
  const response = await getUserCombo();
  if (response.code !== 0) {
    ElMessage.error(response.msg);
    return;
  }
  priceSetting.oncepay = map.once_key ? response.data[map.once_key] : '';
  priceSetting.monpay = map.month_key ? response.data[map.month_key] : '';
  priceSetting.once_nums = map.nums_key ? response.data[map.nums_key] : '';
  priceSetting.month_time = map.time_key ? response.data[map.time_key] : '';
  priceSetting.free_nums = response.data.free_nums;
};

onUnmounted(() => {
  document.removeEventListener('click', closeDropdownOnClickOutside);
});

// 检查是否今日已咨询过该问题
const getMd5Today = () => {
  if (!selectedHealthQuestion.value) return false;

  const cacheKey = buildDailyCacheKey();
  if (!cacheKey) return false;

  return localStorage.getItem(cacheKey) === '1';
};

// 标记今日已咨询
const setMd5Today = () => {
  if (!selectedHealthQuestion.value) return;

  const cacheKey = buildDailyCacheKey();
  if (!cacheKey) return;

  localStorage.setItem(cacheKey, '1');
};

const buildDailyCacheKey = () => {
  if (!selectedHealthQuestion.value) return '';

  const now = new Date();
  const curDateDetail = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`;

  const formatValue = (value) => {
    if (value === null || value === undefined) return '';
    if (typeof value === 'string') return value.trim();
    if (typeof value === 'number' || typeof value === 'boolean') return value;
    if (Array.isArray(value)) {
      return value.map(item => formatValue(item)).join('|');
    }
    try {
      return JSON.stringify(value);
    } catch (error) {
      return String(value);
    }
  };

  const normalizedInputs = {};
  const questionKeys = Array.isArray(selectedHealthQuestion.value.questions) ? selectedHealthQuestion.value.questions : [];
  const seenKeys = new Set();

  questionKeys.forEach(questionKey => {
    normalizedInputs[questionKey] = formatValue(healthInputs.value[questionKey]);
    seenKeys.add(questionKey);
  });

  Object.keys(healthInputs.value || {}).forEach(key => {
    if (!seenKeys.has(key)) {
      normalizedInputs[key] = formatValue(healthInputs.value[key]);
    }
  });

  const signatureObj = {};
  Object.keys(normalizedInputs).sort().forEach(key => {
    signatureObj[key] = normalizedInputs[key];
  });

  const inputSignature = encodeURIComponent(JSON.stringify(signatureObj));

  return `health_${curDateDetail}_${selectedHealthQuestion.value.id}_${inputSignature}`;
};

// 选择健康咨询问题
const selectHealthQuestion = (question) => {
  question.prompts = typeof question.prompts == 'string' ? t(question.prompts).split(',') : question.prompts;
  selectedHealthQuestion.value = question;
  showDropdown.value = false;
  // 重置输入
  healthInputs.value = {};
};

// 触发文件上传
const fileInput = ref(null);
const triggerUpload = () => {
  fileInput.value.click();
};

// 处理文件上传
const handleFileUpload = (event) => {
  const files = event.target.files;
  if (!files.length) return;

  // 限制上传数量
  const remainingSlots = 4 - healthImages.value.length;
  const filesToProcess = Array.from(files).slice(0, remainingSlots);

  filesToProcess.forEach(file => {
    // 创建预览URL
    const reader = new FileReader();
    reader.onload = (e) => {
      healthImages.value.push({
        file: file,
        url: e.target.result,
        name: file.name
      });
    };
    reader.readAsDataURL(file);
  });

  // 重置input，允许重复选择相同文件
  event.target.value = '';
};

// 移除上传的图片
const removeHealthImage = (index) => {
  healthImages.value.splice(index, 1);
};



// 支付组件引用
const paymentDialog = ref(null);
const currentPackage = ref({
  type: '',
  name: '',
  price: 0
});

// 处理充值点击
const handleRechargeClick = (type) => {
  // 获取分类名称（这里直接使用默认名称，因为useTeamType中没有分类名称字典）
  let categoryName = t('health_consultation');
  if (healthCategoryId.value == 7) {
    categoryName = t('personal_analysis');
  } else if (healthCategoryId.value == 8) {
    categoryName = t('career_advice');
  } else if (healthCategoryId.value == 9) {
    categoryName = t('emotional_advice');
  } else if (healthCategoryId.value == 10) {
    categoryName = t('public_relations_audit');
  } else if ([11, 12, 13, 14, 15, 16, 17].includes(Number(healthCategoryId.value))) {
    categoryName = t('team_package');
  } else if (healthCategoryId.value == 20) {
    categoryName = t('academic_essay');
  } else if (healthCategoryId.value == 19) {
    categoryName = t('health_consultation');
  }

  // 根据当前分类和充值类型设置套餐信息
  if (type === 'once') {
    currentPackage.value = {
      type: map.nums_key || 'once',
      name: `${categoryName} ${t('once_card')}`,
      price: priceSetting.oncepay || 99
    };
  } else if (type === 'month') {
    currentPackage.value = {
      type: map.month_key || 'month',
      name: `${categoryName} ${t('month_card')}`,
      price: priceSetting.monpay || 199
    };
  }

  // 打开支付对话框
  paymentDialog.value.showPayment();
};

// 支付结果处理函数
const handlePaymentSuccess = async () => {
  ElMessage.success(t('payment_success'));
  await getUserCard(); // 刷新套餐信息
};

const handlePaymentCancel = () => {
  ElMessage.info(t('payment_cancel'));
};

const handlePaymentError = (error) => {
  ElMessage.error(t('payment_error') + (error?.message || ''));
};

// 提交健康咨询
const submitHealthConsultation = async () => {
  const isLoggedIn = toogleLoginModal();
  if (!isLoggedIn) return;
  if (!selectedHealthQuestion.value) {
    ElMessage.warning(t('please_select_consultation_item'));
    return;
  }

  // 检查今日是否已经咨询过该问题
  if (getMd5Today()) {
    ElMessage.warning(t('same_question_daily_consultation_once'));
    return;
  }

  // 检查输入是否包含空格（即多选项）
  let hasSpaceInInput = false;
  Object.keys(healthInputs.value).forEach(key => {
    const value = healthInputs.value[key];
    // 跳过日期字段的检查，因为日期可能包含空格
    if (!key.toLowerCase().includes('date') && value && typeof value === 'string' && value.includes(' ')) {
      hasSpaceInInput = true;
    }
  });

  if (hasSpaceInInput) {
    ElMessage.warning(t('no_multiple_options_input'));
    return;
  }

  // 验证必填项
  let hasEmptyRequired = false;
  selectedHealthQuestion.value.questions.forEach((question, index) => {
    const prompt = selectedHealthQuestion.value.prompts[index];
    if (!healthInputs.value[question] && prompt.includes('*')) {
      hasEmptyRequired = true;
    }
  });

  if (hasEmptyRequired) {
    ElMessage.warning(t('please_fill_all_required_fields'));
    return;
  }

  try {
    // 显示加载状态
    if (priceSetting.free_nums > 0) {
      // 如果有免费次数，先显示5秒加载窗口
      loadingStore.startLoading(t('loading_message'));
      // 延迟5秒执行后续操作
      await new Promise(resolve => setTimeout(resolve, 5000));
    } else {
      // 没有免费次数，直接显示正常加载状态
      loadingStore.startLoading(t('loading_message'));
    }

    // 重置打字机效果
    resetTypewriter();

    // 构建请求参数，参考微信小程序的 latestPersonPredict 函数
    const requestData = {
      user_phone: userStore.getUserName.username, // 默认手机号
      question_id: selectedHealthQuestion.value.id,
      time_pay: 0
    };

    // 添加输入的信息
    selectedHealthQuestion.value.questions.forEach((question, index) => {
      requestData[question] = healthInputs.value[question] || '';
    });

    // 如果有日期相关的字段，添加到请求中
    if (healthInputs.value['date']) {
      requestData.date1 = healthInputs.value['date'];
    }
    if (healthInputs.value['startdate']) {
      requestData.startdate = healthInputs.value['startdate'];
    }
    if (healthInputs.value['enddate']) {
      requestData.enddate = healthInputs.value['enddate'];
    }

    // 调用API提交咨询
    const response = await submitHealthQuery(requestData);

    if (response.code === 0 && response.data && response.data.history_id) {
      // 标记今日已咨询
      setMd5Today();

      // 获取history_id
      const historyId = response.data.history_id;

      // 构建获取预测结果的请求参数
      const predictParams = {
        history_id: historyId,
        flag: 0,
        isHidden: 0,
        isIos: 0
      };

      // 调用获取预测结果的API
      try {
        const predictResponse = await getPredict(predictParams);

        console.log('获取预测结果返回:', predictResponse);
        
        // 使用 hook 翻译响应数据
        if (predictResponse.data) {
          predictResponse.data = translateObjectProperties(predictResponse.data);
        }

        // 关闭加载状态
        loadingStore.endLoading();

        if (predictResponse.code === 0) {
          // 构建结果数据结构，用于打字机效果
          const resultData = [];

          // 添加咨询标题部分
          resultData.push({
            title: t('consultation_item'),
            paragraphs: [t(selectedHealthQuestion.value.title)]
          });

          // 添加咨询内容部分
          const contentSection = {
            title: t('consultation_content'),
            paragraphs: []
          };

          selectedHealthQuestion.value.questions.forEach((question, index) => {
            const prompt = selectedHealthQuestion.value.prompts[index];
            const value = healthInputs.value[question] || '未填写';
            contentSection.paragraphs.push(`${prompt}: ${value}`);
          });

          resultData.push(contentSection);

          // 添加结果部分 - 使用格式化函数
          if (predictResponse.data && Object.keys(predictResponse.data).length > 0) {
            const resultSection = {
              title: t('consultation_result'),
              paragraphs: []
            };

            const detail = predictResponse.data;

            // 使用格式化函数处理结果数据
            const formattedParagraphs = formatHealthResult(detail);

            // 添加格式化的段落到结果中
            resultSection.paragraphs = formattedParagraphs;

            resultData.push(resultSection);
          } else {
            resultData.push({
              title: t('consultation_result'),
              paragraphs: [t('no_related_results')]
            });
          }

          // 自定义高亮函数，使用本地的 t 函数
          const customHighlight = (text) => {
            const highlightKeywords = ['uncontrollable_events', 'uncontrollable_events_this_year', 'history_detail_text4', 'history_detail_text5', 'year', 'month', 'day'];
            const shouldHighlight = highlightKeywords.some(keyword =>
              text.includes(keyword) || text.includes(t(keyword))
            );
            
            if (shouldHighlight && text.trim()) {
              return `<span style="background-color: #ffeb3b; padding: 2px 4px; border-radius: 4px; font-weight: bold;">${text}</span>`;
            }
            return text;
          };

          // 设置结果数据并开始打字机效果
          setResultData(resultData);
          startTypingEffect(50, 30, 500, 200, customHighlight);

          // 显示结果区域
          showResult.value = true;
          //重新请求次数
          await getUserCard();
          // 不重置表单，让用户可以看到自己提交的内容和结果的对应关系
        } else {
          ElMessage.error(predictResponse.msg || t('get_result_failed'));
          loadingStore.endLoading();
        }
      } catch (error) {
        console.error('获取预测结果失败:', error);
        loadingStore.endLoading();
        ElMessage.error(t('get_result_failed'));
      }
    } else {
      loadingStore.endLoading();
      ElMessage.error(response.msg || t('submit_failed'));
    }
  } catch (error) {
    console.error('提交健康咨询失败:', error);
    loadingStore.endLoading();
    ElMessage.error(t('submit_failed'));
  }
};

// 格式化健康咨询结果（修改为确保所有模块都显示内容）
const formatHealthResult = (detail) => {
  let aiRes = '';

  // 编号信息 - 所有模块显示
  if (detail.num_sn) {
    aiRes += `${t('num_sn')}: @${detail.num_sn}\n\n`;
  }

  // 问题描述 - 所有模块显示
  if (detail.question_msg) {
    aiRes += `${t(detail.question_msg)}\n\n`;
  }

  // 健康状态 - 移除部分限制条件，更多模块可以显示（但排除中医特殊板块，避免重复）
  if (detail.health_status && detail.is_special_medical != 1 && 
    (detail.contact != 2 || [58, 59, 75].includes(detail.question_id))) {
    aiRes += `❤️ ${t(detail.health_status)}\n\n`;
  }

  // 日期区间 - 所有模块都尝试显示（排除股市，避免重复）
  if (detail.startenddate && detail.startenddate.length > 0 && detail.startenddate !== t('no') &&
      detail.contact_text !== t('stock')) {
    aiRes += `📅 ${t(detail.startenddate)}\n\n`;
  }

  // 年月日信息 - 所有模块都显示
  // const dateInfo = [];
  // if (detail.year_good) {
  //   let yearLine = `📅 ${t('year')} ${detail.year_good} `;
  //   yearLine += detail.is_special ? (detail.hui ? '✅ ' + t('easy_to_achieve') : '❌ ' + t('difficult_to_achieve')) : (detail.date_diff || '');
  //   dateInfo.push(yearLine);
  // }

  // if (detail.month_good) {
  //   let monthLine = `📅 ${t('month')} ${detail.month_good} `;
  //   monthLine += detail.is_special ? (detail.hui ? '✅ ' + t('easy_to_achieve') : '❌ ' + t('difficult_to_achieve')) : (detail.date_diff || '');
  //   dateInfo.push(monthLine);
  // }

  // if (detail.day_good) {
  //   let dayLine = `📅 ${t('day')} ${detail.day_good} `;
  //   dayLine += detail.is_special ? (detail.hui ? '✅ ' + t('easy_to_achieve') : '❌ ' + t('difficult_to_achieve')) : (detail.date_diff || '');
  //   dateInfo.push(dayLine);
  // }

  // 只有当有日期信息时才添加到结果中
  // if (dateInfo.length > 0) {
  //   aiRes += dateInfo.join('\n') + '\n\n';
  // }

  // 不可控事件 - 所有模块都显示（排除有指定日期的情况，避免重复）
  if ((detail.is_coflict !== undefined || detail.is_special !== undefined) && 
      !detail.isAssignDate) {
    aiRes += `📅 ${t('uncontrollable_events')} `;
    aiRes += (detail.is_coflict == 1 && detail.is_special == 1) ? '✅ ' + t('easy_to_achieve') : '❌ ' + t('difficult_to_achieve');
    aiRes += `\n`;
  }

  // 指定日期相关 - 所有模块都显示
  if (detail.isAssignDate && detail.date1) {
    if (detail.deal_152232 == 0) {
      if (detail.is_month_coflict != 1 && detail.is_date_coflict != 1) {
        aiRes += `📅 ${detail.date1} `;
      }
      aiRes += (detail.is_month_coflict == 1 || detail.is_date_coflict == 1) ?
        '✅ ' + t('easy_to_achieve') : '❌ ' + t('difficult_to_achieve');
      aiRes += `\n`;
    }

    // 第二层不可控事件 - 所有模块都显示（有date1时显示）
    if (detail.date1 && detail.is_second_coflict !== undefined) {
      aiRes += `⚠️ ${t('uncontrollable_events')} `;
      aiRes += (detail.is_second_coflict == 1 && detail.is_special == 1) ?
              '✅ ' + t('easy_to_achieve') : '❌ ' + t('difficult_to_achieve');
      aiRes += `\n`;
    }

    // 本年度不可控事件 - 仅在没有指定日期时显示
    if (!detail.date1 && detail.is_second_coflict !== undefined) {
      aiRes += `📅 ${t('uncontrollable_events_this_year')} `;
      aiRes += (detail.is_second_coflict == 1 && detail.is_special == 1) ?
              '✅ ' + t('easy_to_achieve') : '❌ ' + t('difficult_to_achieve');
      aiRes += `\n`;
    }

    // 预期结果 - 仅在有date1且deal_152232不为0时显示，避免与上面的日期判断重复
    if (detail.date1 && detail.deal_152232 != 0 && detail.is_coflict !== undefined) {
      aiRes += `🚨 ${t('uncontrollable_events')} ${t('expected_result')} `;
      aiRes += (detail.is_coflict == 1 && detail.is_special == 1) ?
        '✅ ' + t('easy_to_achieve') : '❌ ' + t('difficult_to_achieve');
      aiRes += `\n`;
    }
  }

  // 股市特殊处理 - 保持原逻辑
  if (detail.contact_text === t('stock') && detail.startenddate && detail.startenddate.length > 0) {
    if (detail.startenddate !== t('no')) {
      aiRes += `📈 ${detail.startenddate} `;
      if (detail.is_special) {
        aiRes += detail.easy != 0 ? '✅ ' + t('easy_to_achieve') : '❌ ' + t('difficult_to_achieve');
      } else {
        aiRes += `${detail.date_diff || ''}`;
      }
      aiRes += `\n\n`;
    }
  }

  // 有无利益 - 所有模块都显示
  if (detail.last_num_text) {
    aiRes += `💰 ${t('profit')}: ${t(detail.last_num_text)}\n\n`;
  }

  // 中医特殊板块 - 保持原逻辑
  if (detail.is_special_medical == 1) {
    aiRes += `🌿 ${t('improve_time')}: \n`;
    if (detail.ta_idea_list && Array.isArray(detail.ta_idea_list)) {
      detail.ta_idea_list.forEach(item => {
        aiRes += `   → ${item}\n`;
      });
    }
    aiRes += `\n`;

    if (detail.health_status) {
      aiRes += `❤️ ${t(detail.health_status)}\n\n`;
    }
  }

  // 心态与情绪 - 所有模块都显示（移除 is_special_medical != 1 限制）
  /*if (detail.me_xintai || detail.things_degree || detail.me_xinli) {
    if (detail.result_title && detail.result_title.title_8) {
      aiRes += `📌 ${detail.result_title.title_8}\n`;
    } else {
      aiRes += `📌 ${t('mind_and_mood')}\n`;
    }
    aiRes += `   → ${detail.me_xintai || ''}\n\n`;

    if (detail.result_title && detail.result_title.title_9) {
      aiRes += `📌 ${t(detail.result_title.title_9)}\n`;
    } else {
      aiRes += `📌 ${t('difficulty_of_thing')}\n`;
    }
    aiRes += `   → ${detail.things_degree || ''}\n\n`;

    if (detail.result_title && detail.result_title.title_10) {
      aiRes += `📌 ${t(detail.result_title.title_10)}\n`;
    } else {
      aiRes += `📌 ${t('mental_advice')}\n`;
    }
    aiRes += `   → ${t(detail.me_xinli || '')}\n\n`;
  }*/

  // 解决方案 - 所有模块都显示
  // if (detail.solution) {
  //   aiRes += `— ${t('can_solve_problem')} —\n`;
  //   aiRes += detail.solution;
  //   aiRes += `\n\n`;
  // }

  // 增强兜底机制 - 确保所有返回内容都能显示
  if (aiRes.trim().length === 0) {
    // 尝试显示所有可能的字段
    Object.keys(detail).forEach(key => {
      const value = detail[key];
      if (value && typeof value === 'string' && value.trim() &&
          !['question_id', 'contact', 'is_special_medical', 'is_special', 'hui'].includes(key)) {
        aiRes += `${key}: ${value}\n\n`;
      }
    });

    // 如果还是没有内容，显示原始结果
    if (aiRes.trim().length === 0 && detail.result) {
      aiRes = detail.result;
    }
  }

  // 将格式化的内容分段并返回
  if (aiRes.trim()) {
    // 分段处理，过滤空段落，并确保每个段落都有内容
    const paragraphs = aiRes
      .split('\n\n')
      .map(para => para.trim())
      .filter(para => para.length > 0);
    return paragraphs;
  } else {
    // 最终兜底：显示整个detail对象的JSON
    return [`${t('consultation_result')}: ${JSON.stringify(detail, null, 2)}`];
  }
};

// 获取健康咨询问题列表
const fetchHealthQuestions = async () => {
  // 这里可以添加实际的API调用
  const response = await getQuestionList(healthCategoryId.value);
  if (response.code === 0 && response.data.length > 0) {
    healthQuestions.value = response.data;
  }
};


</script>

<style lang="less" scoped>
/* 健康咨询视图样式 */
.health-view {
  display: flex;
  flex-direction: column;
  min-height: 100%;
  position: relative;
}

.health-container {
  flex: 1;
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
  width: 100%;
}

.health-section-title {
  text-align: center;
  margin-bottom: 20px;
  color: #3f51b5;
  font-weight: 600;
  font-size: 18px;
}

.health-category {
  margin-bottom: 30px;
}

.health-dropdown {
  position: relative;
  width: 100%;
}

.health-category-selector {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
  background-color: #fff;
  transition: all 0.3s;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
  color: #333333;
  font-weight: 500;
}

.health-category-selector:hover {
  border-color: #2e7d32;
  background-color: #f9fff9;
}

.health-category-selector .placeholder {
  color: #555555;
  font-weight: 500;
}

.selector-icon {
  color: #2e7d32;
  transition: transform 0.3s ease;
  font-weight: bold;
}

.selector-icon.rotated {
  transform: rotate(180deg);
}

.health-dropdown-menu {
  position: absolute;
  top: 100%;
  left: 0;
  width: 100%;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
  z-index: 100;
  margin-top: 5px;
  max-height: 250px;
  overflow-y: auto;
  border: 1px solid #e8eaf6;
  animation: fadeIn 0.2s ease-in-out;
  padding: 4px 0;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.health-dropdown-item {
  padding: 12px 16px;
  cursor: pointer;
  transition: all 0.2s;
  border-bottom: 1px solid #e8f5e9;
  color: #333333;
  font-weight: 500;
}

.health-dropdown-item:last-child {
  border-bottom: none;
}

.health-dropdown-item:hover {
  background-color: #e8eaf6;
  color: #3f51b5;
  font-weight: 600;
}

.health-form {
  margin-bottom: 30px;
}

.health-form-item {
  margin-bottom: 20px;
}

.health-form-item label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333333;
}

.health-input {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  transition: all 0.3s;
}

.health-input:focus {
  outline: none;
  border-color: #3f51b5;
  box-shadow: 0 0 0 2px rgba(63, 81, 181, 0.2);
}

/* 日期选择器样式 */
.health-date-input {
  width: 100% !important;
}

/* 覆盖Element Plus默认样式 */
:deep(.el-date-editor.el-input) {
  width: 100% !important;
}

:deep(.el-input__wrapper) {
  width: 100% !important;
  padding: 0;
  height: 38px;
  line-height: 38px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  transition: all 0.3s;
  box-shadow: none;
  padding-left: 10px;
}

:deep(.el-input__wrapper:hover) {
  border-color: #3f51b5;
}

:deep(.el-input__wrapper.is-focus) {
  border-color: #3f51b5;
  box-shadow: 0 0 0 2px rgba(63, 81, 181, 0.2);
}

.health-upload {
  margin-bottom: 30px;
}

.upload-area {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.uploaded-image {
  width: 120px;
  height: 120px;
  border-radius: 4px;
  overflow: hidden;
  position: relative;
}

.uploaded-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-delete {
  position: absolute;
  top: 5px;
  right: 5px;
  width: 24px;
  height: 24px;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 18px;
}

.upload-button {
  width: 120px;
  height: 120px;
  border: 2px dashed #c0caf5;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s;
  background-color: rgba(63, 81, 181, 0.03);
  box-shadow: 0 2px 8px rgba(63, 81, 181, 0.05);
}

.upload-button:hover {
  border-color: #3f51b5;
  color: #3f51b5;
  background-color: rgba(63, 81, 181, 0.08);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(63, 81, 181, 0.12);
}

.upload-icon {
  font-size: 28px;
  margin-bottom: 8px;
  color: #5c6bc0;
  width: 40px;
  height: 40px;
  background-color: rgba(92, 107, 192, 0.1);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
}

.health-submit {
  text-align: center;
}

.health-result-section {
  margin-bottom: 20px;

  .health-section-title {
    font-size: 18px;
    font-weight: 600;
    margin-bottom: 15px;
    color: #333;
  }

  .result-content {
    background-color: #fff;
    border-radius: 8px;
    padding: 15px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
}

.health-submit {
  margin-top: 30px;
  text-align: center;

  .submit-button {
    background-color: #1890ff;
    color: white;
    border: none;
    border-radius: 4px;
    padding: 12px 24px;
    font-size: 16px;
    cursor: pointer;
    transition: background-color 0.3s;

    &:hover {
      background-color: #40a9ff;
    }

    &:disabled {
      background-color: #bfbfbf;
      cursor: not-allowed;
    }
  }
}

.submit-button {
  padding: 12px 24px;
  background: linear-gradient(135deg, #3f51b5 0%, #5c6bc0 100%);
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 500;
  transition: all 0.3s;
  box-shadow: 0 2px 8px rgba(63, 81, 181, 0.3);
}

.submit-button:hover {
  background: linear-gradient(135deg, #3949ab 0%, #5c6bc0 100%);
  box-shadow: 0 4px 12px rgba(63, 81, 181, 0.4);
  transform: translateY(-1px);
}

.submit-button:disabled {
  background: linear-gradient(135deg, #9fa8da 0%, #b3b8d3 100%);
  cursor: not-allowed;
  box-shadow: none;
  transform: none;
}

/* 状态显示区域样式 */
.health-status-area {
  margin: 20px 0;
  padding: 15px;
  border-radius: 8px;
  background-color: #f8f9fa;
}

.status-block {
  display: flex;
  align-items: center;
  padding: 10px;
  border-radius: 6px;
}

.expiry-time {
  background-color: #fff3cd;
  border: 1px solid #ffeeba;
}

.free-count {
  background-color: #d4edda;
  border: 1px solid #c3e6cb;
}

.usage-count {
  background-color: #e2f0fb;
  border: 1px solid #bee5eb;
}

.status-icon {
  font-size: 20px;
  margin-right: 10px;
}

.status-text {
  font-size: 16px;
  font-weight: 500;
}

/* 支付选项样式 */
.payment-options {
  flex-direction: column;
  background-color: #f8f9fa;
  border: 1px solid #e9ecef;
}

.payment-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 12px;
  text-align: center;
}

.payment-buttons {
  display: flex;
  justify-content: space-around;
}

.payment-button {
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.once-card {
  background-color: #4caf50;
  color: white;
}

.month-card {
  background-color: #2196f3;
  color: white;
}

.payment-button:hover {
  opacity: 0.9;
  transform: translateY(-2px);
}
</style>